package com.rudisoft.analysis;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.StreamTokenizer;
import java.util.ArrayList;

public class StateChartGenerator {

	private ArrayList<File> filePaths;

	/**
	 * this program is supposed to give an overview of the EventListeners of a
	 * program that is available in source code
	 * 
	 * @param string
	 */
	public StateChartGenerator(String string) {
		File dir = new File(string);
		try {
			if (dir.exists() && dir.isDirectory()) {
				System.out.println("inspecting dir [" + string + "]");

				// create file list
				filePaths = new ArrayList<File>();
				parsedir(dir);

				// find files that implement EventListener
				findEventListeners();

				System.out.println("[" + filePaths.size()
						+ "] java files found");
			} else {
				System.err.println("file [" + string + "] is not a directory");
			}

		} catch (Exception e) {
			System.err.println("error while looking for file [" + string + "]");
		}
	}

	private void findEventListeners() {
		try {
			for (int i = 0; i < this.filePaths.size(); i++) {
				inspectFile(this.filePaths.get(i));
			}

		} catch (Exception e) {
			System.err
					.println("error while looking for EventListerner declarations");
		}

	}

	private void inspectFile(File file) {
		try {
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader is = new InputStreamReader(fis);
			LineNumberReader lr = new LineNumberReader(is);
			
			for(String line = lr.readLine(); line!=null; line=lr.readLine()){
				line = line.trim();
				System.out.println(line);
				
			}
			

			fis.close();
		} catch (Exception e) {
			System.err.println("error while inspecting file ["
					+ file.getAbsolutePath() + "]");
		}

	}

	/**
	 * create the file list
	 * 
	 * @param dir
	 */
	private void parsedir(File dir) {
		try {
			if (dir.isDirectory()) {
				File[] list = dir.listFiles();
				for (int i = 0; i < list.length; i++) {
					if (list[i].isDirectory()) {
						parsedir(list[i]);
					} else if (list[i].getName().endsWith(".java")) {
						System.out.println("java file found: ["
								+ list[i].getName() + "]");
						filePaths.add(list[i]);
					} else {
						// System.out.println("unknown file type found:
						// ["+list[i].getName()+"]");
					}
				}
			} else {
				System.out.println("file foud: [" + dir.getName() + "]");
			}
		} catch (Exception e) {
			System.err.println("error while parsing directory ["
					+ dir.getAbsolutePath() + "]");
			System.exit(-1);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length == 1) {
			new StateChartGenerator(args[0]);
		} else {
			System.err.println("please provide a directory name");
		}

	}

}
